//
//  APPTools.m
//  Tools
//
//  Created by Jasmine on 16/6/16.
//  Copyright © 2016年 Jasmine. All rights reserved.
//

#import "APPTools.h"
#import "AFNetworking.h"

@implementation APPTools
+ (void)GETWithURL:(NSString *)urlStr
               par:(NSDictionary *)dic
           success:(void (^)(id))responseObj filed:(void (^)(NSError *))err
{
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    // 中文转码
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    [man GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObj(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        err(error);
        
        
        
        
    }];
}

+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
#pragma mark - 本地缓存
#if 1
    // 哈希转码
    NSString *path = [NSString stringWithFormat:@"%ld",(unsigned long)[urlStr hash]];
    
    NSString *finalOfPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:path];
#endif
    
    [man POST:urlStr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
#if 1
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:finalOfPath];
#endif
        
        
        response(responseObject);
        
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
#if 1
        // 反归档
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:finalOfPath];
        response(result);
#endif
        err(error);
        
    }];
    
}
@end
